<template>
  <div class="page-structure">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">页面结构管理</h1>
        <p class="page-description">查看和管理系统的页面层次结构、路由配置和组件关系</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="refreshStructure">
          <el-icon><Refresh /></el-icon>
          刷新结构
        </el-button>
        <el-button @click="exportStructure">
          <el-icon><Download /></el-icon>
          导出结构
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :span="6" v-for="stat in systemStats" :key="stat.key">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon" :style="{ color: stat.color }">
                <el-icon :size="32">
                  <component :is="stat.icon" />
                </el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ stat.value }}</div>
                <div class="stat-label">{{ stat.label }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 页面结构树 -->
    <div class="structure-section">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>页面结构树</span>
            <div class="header-controls">
              <el-input
                v-model="searchKeyword"
                placeholder="搜索页面..."
                clearable
                style="width: 200px"
                @input="handleSearch"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
              <el-button-group style="margin-left: 12px">
                <el-button 
                  :type="viewMode === 'tree' ? 'primary' : ''"
                  @click="viewMode = 'tree'"
                >
                  <el-icon><Grid /></el-icon>
                  树形视图
                </el-button>
                <el-button 
                  :type="viewMode === 'table' ? 'primary' : ''"
                  @click="viewMode = 'table'"
                >
                  <el-icon><List /></el-icon>
                  表格视图
                </el-button>
              </el-button-group>
            </div>
          </div>
        </template>

        <!-- 树形视图 -->
        <div v-if="viewMode === 'tree'" class="tree-view">
          <el-tree
            :data="filteredRouteTree"
            :props="treeProps"
            :expand-on-click-node="false"
            :default-expand-all="true"
            node-key="path"
            class="route-tree"
          >
            <template #default="{ data }">
              <div class="tree-node">
                <div class="node-info">
                  <el-icon class="node-icon" :color="getNodeColor(data.type)">
                    <component :is="getNodeIcon(data.type)" />
                  </el-icon>
                  <span class="node-title">{{ data.title || data.name }}</span>
                  <el-tag 
                    :type="getRouteType(data.meta?.requiresAuth)" 
                    size="small"
                    class="auth-tag"
                  >
                    {{ data.meta?.requiresAuth ? '需要认证' : '公开访问' }}
                  </el-tag>
                </div>
                <div class="node-actions">
                  <el-button size="small" type="primary" text @click="viewRouteDetail(data)">
                    查看详情
                  </el-button>
                  <el-button size="small" type="success" text @click="navigateToRoute(data)">
                    访问页面
                  </el-button>
                </div>
              </div>
            </template>
          </el-tree>
        </div>

        <!-- 表格视图 -->
        <div v-else class="table-view">
          <el-table :data="flatRouteList" stripe>
            <el-table-column prop="path" label="路由路径" min-width="200" />
            <el-table-column prop="name" label="路由名称" width="150" />
            <el-table-column prop="title" label="页面标题" width="150" />
            <el-table-column prop="component" label="组件路径" min-width="250" show-overflow-tooltip />
            <el-table-column label="认证要求" width="100">
              <template #default="{ row }">
                <el-tag :type="getRouteType(row.meta?.requiresAuth)" size="small">
                  {{ row.meta?.requiresAuth ? '需要认证' : '公开' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="{ row }">
                <el-button size="small" type="primary" @click="viewRouteDetail(row)">
                  详情
                </el-button>
                <el-button size="small" type="success" @click="navigateToRoute(row)">
                  访问
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </div>

    <!-- 路由详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="路由详情"
      width="60%"
      class="route-detail-dialog"
    >
      <div v-if="currentRoute" class="route-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="路由路径">{{ currentRoute.path }}</el-descriptions-item>
          <el-descriptions-item label="路由名称">{{ currentRoute.name }}</el-descriptions-item>
          <el-descriptions-item label="页面标题">{{ currentRoute.title || currentRoute.meta?.title }}</el-descriptions-item>
          <el-descriptions-item label="组件路径">{{ currentRoute.component }}</el-descriptions-item>
          <el-descriptions-item label="认证要求">
            <el-tag :type="getRouteType(currentRoute.meta?.requiresAuth)">
              {{ currentRoute.meta?.requiresAuth ? '需要认证' : '公开访问' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="全屏模式">
            <el-tag :type="currentRoute.meta?.fullscreen ? 'success' : 'info'">
              {{ currentRoute.meta?.fullscreen ? '是' : '否' }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>

        <div v-if="currentRoute.meta" class="meta-info">
          <h4>元数据信息</h4>
          <el-table :data="getMetaData(currentRoute.meta)" size="small">
            <el-table-column prop="key" label="属性" width="150" />
            <el-table-column prop="value" label="值" />
          </el-table>
        </div>

        <div v-if="currentRoute.children && currentRoute.children.length" class="children-info">
          <h4>子路由 ({{ currentRoute.children.length }})</h4>
          <el-table :data="currentRoute.children" size="small">
            <el-table-column prop="path" label="路径" />
            <el-table-column prop="name" label="名称" />
            <el-table-column prop="title" label="标题" />
          </el-table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  Refresh, Download, Search, Grid, List, 
  Document, FolderOpened, Connection, Monitor
} from '@element-plus/icons-vue'

// 路由实例
const router = useRouter()

// 响应式数据
const searchKeyword = ref('')
const viewMode = ref('tree')
const detailDialogVisible = ref(false)
const currentRoute = ref(null)

// 系统统计数据
const systemStats = ref([
  {
    key: 'totalRoutes',
    label: '总路由数',
    value: '0',
    color: '#409EFF',
    icon: 'Connection'
  },
  {
    key: 'totalPages',
    label: '页面数量',
    value: '0',
    color: '#67C23A',
    icon: 'Document'
  },
  {
    key: 'authRoutes',
    label: '需认证路由',
    value: '0',
    color: '#E6A23C',
    icon: 'Monitor'
  },
  {
    key: 'publicRoutes',
    label: '公开路由',
    value: '0',
    color: '#F56C6C',
    icon: 'FolderOpened'
  }
])

// 路由树数据
const routeTree = ref([])
const flatRouteList = ref([])

// 树形组件配置
const treeProps = {
  children: 'children',
  label: 'title'
}

// 计算属性
const filteredRouteTree = computed(() => {
  if (!searchKeyword.value) {
    return routeTree.value
  }
  
  return filterRouteTree(routeTree.value, searchKeyword.value.toLowerCase())
})

// 方法
const refreshStructure = () => {
  loadRouteStructure()
  ElMessage.success('结构已刷新')
}

const exportStructure = () => {
  const data = JSON.stringify(routeTree.value, null, 2)
  const blob = new Blob([data], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = 'page-structure.json'
  a.click()
  URL.revokeObjectURL(url)
  ElMessage.success('结构已导出')
}

const handleSearch = () => {
  // 搜索逻辑在computed中处理
}

const viewRouteDetail = (route) => {
  currentRoute.value = route
  detailDialogVisible.value = true
}

const navigateToRoute = (route) => {
  if (route.path && route.path !== '/') {
    router.push(route.path)
    ElMessage.success(`正在跳转到 ${route.title || route.name}`)
  } else {
    ElMessage.warning('该路由无法直接访问')
  }
}

const getNodeColor = (type) => {
  const colors = {
    layout: '#909399',
    page: '#409EFF',
    redirect: '#E6A23C'
  }
  return colors[type] || '#606266'
}

const getNodeIcon = (type) => {
  const icons = {
    layout: 'FolderOpened',
    page: 'Document',
    redirect: 'Connection'
  }
  return icons[type] || 'Document'
}

const getRouteType = (requiresAuth) => {
  return requiresAuth ? 'warning' : 'success'
}

const getMetaData = (meta) => {
  if (!meta) return []
  
  return Object.entries(meta).map(([key, value]) => ({
    key,
    value: typeof value === 'object' ? JSON.stringify(value) : String(value)
  }))
}

const filterRouteTree = (routes, keyword) => {
  return routes.filter(route => {
    const matchesKeyword = 
      (route.title && route.title.toLowerCase().includes(keyword)) ||
      (route.name && route.name.toLowerCase().includes(keyword)) ||
      (route.path && route.path.toLowerCase().includes(keyword))
    
    if (matchesKeyword) {
      return true
    }
    
    if (route.children && route.children.length) {
      const filteredChildren = filterRouteTree(route.children, keyword)
      if (filteredChildren.length > 0) {
        route.children = filteredChildren
        return true
      }
    }
    
    return false
  })
}

const loadRouteStructure = () => {
  // 获取路由配置
  const routes = router.getRoutes()
  
  // 构建路由树
  const tree = buildRouteTree(routes)
  routeTree.value = tree
  
  // 构建扁平列表
  const flatList = flattenRoutes(routes)
  flatRouteList.value = flatList
  
  // 更新统计数据
  updateStats(routes)
}

const buildRouteTree = (routes) => {
  // 这里简化处理，实际项目中需要根据路由配置构建完整的树结构
  return routes
    .filter(route => !route.path.includes(':') && route.path !== '*')
    .map(route => ({
      ...route,
      title: route.meta?.title || route.name,
      type: route.component ? 'page' : 'layout',
      children: route.children || []
    }))
}

const flattenRoutes = (routes) => {
  const result = []
  
  const flatten = (routeList, parentPath = '') => {
    routeList.forEach(route => {
      if (route.path && !route.path.includes(':')) {
        result.push({
          ...route,
          title: route.meta?.title || route.name,
          component: route.component?.toString() || 'N/A'
        })
      }
      
      if (route.children) {
        flatten(route.children, route.path)
      }
    })
  }
  
  flatten(routes)
  return result
}

const updateStats = (routes) => {
  const totalRoutes = routes.length
  const authRoutes = routes.filter(r => r.meta?.requiresAuth).length
  const publicRoutes = totalRoutes - authRoutes
  const totalPages = routes.filter(r => r.component).length
  
  systemStats.value[0].value = totalRoutes.toString()
  systemStats.value[1].value = totalPages.toString()
  systemStats.value[2].value = authRoutes.toString()
  systemStats.value[3].value = publicRoutes.toString()
}

// 生命周期
onMounted(() => {
  loadRouteStructure()
})
</script>

<style scoped>
.page-structure {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header-content h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #303133;
}

.header-content p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.stats-section {
  margin-bottom: 20px;
}

.stat-card {
  height: 100px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
  padding: 16px;
}

.stat-icon {
  margin-right: 16px;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.structure-section {
  background: white;
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-controls {
  display: flex;
  align-items: center;
}

.tree-view,
.table-view {
  min-height: 400px;
}

.route-tree {
  margin-top: 16px;
}

.tree-node {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding: 4px 8px;
}

.node-info {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.node-icon {
  font-size: 16px;
}

.node-title {
  font-weight: 500;
  color: #303133;
}

.auth-tag {
  margin-left: 8px;
}

.node-actions {
  display: flex;
  gap: 4px;
}

.node-actions .el-button--primary.is-text {
  color: #ffffff !important;
}

.node-actions .el-button--primary.is-text:hover {
  color: #ffffff !important;
  background-color: rgba(255, 255, 255, 0.1) !important;
}

.route-detail {
  padding: 16px 0;
}

.meta-info,
.children-info {
  margin-top: 20px;
}

.meta-info h4,
.children-info h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #303133;
}

.route-detail-dialog :deep(.el-dialog__body) {
  max-height: 60vh;
  overflow-y: auto;
}
</style>
